//
//  HMSegmentedControl.m
//  HMSegmentedControlExample
//
//  Created by Hesham Abd-Elmegid on 23/12/12.
//  Copyright (c) 2012 Hesham Abd-Elmegid. All rights reserved.
//

#import "HMSegmentedControl.h"
#import <QuartzCore/QuartzCore.h>

@interface HMSegmentedControl ()
{
    CALayer *selectedSegmentLayer;
    CGFloat segmentWidth;
}
@end

@implementation HMSegmentedControl

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    if (self) {
        [self setDefaults];
    }
    
    return self;
}

- (id)initWithSectionTitles:(NSArray *)sectiontitles {
    self = [super initWithFrame:CGRectZero];
    
    if (self) {
        sectionTitleArr = sectiontitles;
        [self setDefaults];
    }
    
    return self;
}

// 设置默认属性
- (void)setDefaults {
    //font = [UIFont fontWithName:@"STHeitiSC-Light" size:15.0f];
    font = [UIFont boldSystemFontOfSize:15];
    textColor = [UIColor blackColor];
    self.backgroundColor = [AOColorFormat colorWithHexString:@"#f4f9fe"];
    
    separateLineColor = [AOColorFormat colorWithHexString:@"#bababa"];
    selectionIndicatorColor = [AOColorFormat colorWithHexString:@"#4499ee"];
    self.selectedIndex = 0;
    segmentEdgeInset = UIEdgeInsetsMake(0, 5, 0, 5);
    height = 35.0f;
    separateLineHeight = 0.5f;//分割线高度（厚度）
    selectionIndicatorHeight = 2.0f;//指示器高度
    selectionIndicatorMode = HMSelectionIndicatorFillsSegment;//指示器长度
    
    selectedSegmentLayer = [CALayer layer];
}

#pragma mark - Drawing

- (void)drawRect:(CGRect)rect
{
    [self.backgroundColor set];
    UIRectFill([self bounds]);
    
    [textColor set];
    
    [sectionTitleArr enumerateObjectsUsingBlock:^(id titleString, NSUInteger idx, BOOL *stop) {
        CGFloat stringHeight = [titleString sizeWithFont:font].height;
        CGFloat y = ((height - selectionIndicatorHeight) / 2) + (selectionIndicatorHeight - stringHeight / 2);
        CGRect rect = CGRectMake(segmentWidth * idx, y, segmentWidth, stringHeight);
        
        [titleString drawInRect:rect withFont:font lineBreakMode:NSLineBreakByClipping alignment:NSTextAlignmentCenter];
        
        //view上下分隔线
//        CALayer *viewHeaderLineLayer = [CALayer layer];
//        viewHeaderLineLayer.frame = CGRectMake(self.frame.origin.x, self.bounds.origin.y, self.bounds.size.width, separateLineHeight);
//        viewHeaderLineLayer.backgroundColor = separateLineColor.CGColor;
//        [self.layer addSublayer:viewHeaderLineLayer];
        
        CALayer *viewFooterLineLayer = [CALayer layer];
        
        viewFooterLineLayer.frame = CGRectMake(self.frame.origin.x, self.bounds.origin.y+self.bounds.size.height-separateLineHeight, self.bounds.size.width, separateLineHeight);
        viewFooterLineLayer.backgroundColor = separateLineColor.CGColor;
        [self.layer addSublayer:viewFooterLineLayer];
        
        // section分割线
        for (int i = 0; i < sectionTitleArr.count; i++) {
            CALayer *separateLineLayer = [CALayer layer];
            separateLineLayer.frame = CGRectMake(segmentWidth * i, self.bounds.origin.y, separateLineHeight, self.bounds.size.height);;
            separateLineLayer.backgroundColor = separateLineColor.CGColor;
            [self.layer addSublayer:separateLineLayer];
        }
        
        // 选中指示器frame
        selectedSegmentLayer.frame = [self frameForSelectionIndicator];
        selectedSegmentLayer.backgroundColor = selectionIndicatorColor.CGColor;
        [self.layer addSublayer:selectedSegmentLayer];
    }];
}

- (CGRect)frameForSelectionIndicator {
    CGFloat stringWidth = [[sectionTitleArr objectAtIndex:_selectedIndex] sizeWithFont:font].width;
    
    if (selectionIndicatorMode == HMSelectionIndicatorResizesToStringWidth) {
        CGFloat widthTillEndOfSelectedIndex = (segmentWidth * _selectedIndex) + segmentWidth;
        CGFloat widthTillBeforeSelectedIndex = (segmentWidth * _selectedIndex);
        
        CGFloat x = ((widthTillEndOfSelectedIndex - widthTillBeforeSelectedIndex) / 2) + (widthTillBeforeSelectedIndex - stringWidth / 2);
        
        // Indicator位置
        return CGRectMake(x, self.bounds.size.height -selectionIndicatorHeight, stringWidth, selectionIndicatorHeight);
    } else {
        // Indicator位置
        return CGRectMake(segmentWidth * _selectedIndex, self.bounds.size.height -selectionIndicatorHeight, segmentWidth, selectionIndicatorHeight);
    }
}

- (void)updateSegmentsRects {
    // If there's no frame set, calculate the width of the control based on the number of segments and their size
    if (CGRectIsEmpty(self.frame)) {
        segmentWidth = 0;
        
        for (NSString *titleString in sectionTitleArr) {
            CGFloat stringWidth = [titleString sizeWithAttributes:@{NSFontAttributeName: font}].width + segmentEdgeInset.left + segmentEdgeInset.right;
            segmentWidth = MAX(stringWidth, segmentWidth);
        }
        
        self.bounds = CGRectMake(0, 0, segmentWidth * sectionTitleArr.count, height);
    } else {
        segmentWidth = self.bounds.size.width / sectionTitleArr.count;
        height = self.bounds.size.height;
    }
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    // Control is being removed
    if (newSuperview == nil)
        return;
    
    [self updateSegmentsRects];
}

#pragma mark - Touch

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self];
    
    if (CGRectContainsPoint(self.bounds, touchLocation)) {
        NSInteger segment = touchLocation.x / segmentWidth;
        
        if (segment != _selectedIndex) {
            [self setSelectedIndex:segment animated:YES];
        }
    }
}

#pragma mark -

- (void)setSelectedIndex:(NSInteger)index {
    [self setSelectedIndex:index animated:NO];
}

- (void)setSelectedIndex:(NSUInteger)index animated:(BOOL)animated {
    _selectedIndex = index;

    if (animated) {
        // Restore CALayer animations
        selectedSegmentLayer.actions = nil;
        
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.15f];
        [CATransaction setCompletionBlock:^{
            if (self.superview) {
                [self sendActionsForControlEvents:UIControlEventValueChanged];
            }
            
            if (self.indexChangeBlock) {
                self.indexChangeBlock(index);
            }
        }];
        selectedSegmentLayer.frame = [self frameForSelectionIndicator];
        [CATransaction commit];
    } else {
        // Disable CALayer animations
        NSMutableDictionary *newActions = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNull null], @"position", [NSNull null], @"bounds", nil];
        selectedSegmentLayer.actions = newActions;
        
        selectedSegmentLayer.frame = [self frameForSelectionIndicator];
        
        if (self.superview) {
            [self sendActionsForControlEvents:UIControlEventValueChanged];
        }
        
        if (self.indexChangeBlock) {
            self.indexChangeBlock(index);
        }
    }
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    
    if (sectionTitleArr) {
        [self updateSegmentsRects];
    }
    
    [self setNeedsDisplay];
}

- (void)setBounds:(CGRect)bounds {
    [super setBounds:bounds];
    
    if (sectionTitleArr) {
        [self updateSegmentsRects];
    }
    
    [self setNeedsDisplay];
}

@end
